import json
import os
from pathlib import Path
from typing import List, Dict, Optional
from datetime import datetime
from app.config import settings
from app.utils.logger import logger

class VideoManager:
    def __init__(self):
        self.upload_dir = Path(settings.UPLOAD_DIR)
        self.metadata_file = self.upload_dir / "video_metadata.json"
        self.ensure_metadata_file()
    
    def ensure_metadata_file(self):
        """确保元数据文件存在"""
        if not self.metadata_file.exists():
            self.save_metadata({})
    
    def load_metadata(self) -> Dict:
        """加载视频元数据"""
        try:
            if self.metadata_file.exists():
                with open(self.metadata_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            return {}
        except Exception as e:
            logger.error(f"加载视频元数据失败: {e}")
            return {}
    
    def save_metadata(self, metadata: Dict):
        """保存视频元数据"""
        try:
            with open(self.metadata_file, 'w', encoding='utf-8') as f:
                json.dump(metadata, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存视频元数据失败: {e}")
    
    def add_video_record(self, filename: str, original_name: str, file_size: int) -> bool:
        """添加视频记录"""
        try:
            metadata = self.load_metadata()
            metadata[filename] = {
                "original_name": original_name,
                "file_size": file_size,
                "upload_time": datetime.now().isoformat(),
                "video_url": f"{settings.VIDEO_BASE_URL}/videos/{filename}"
            }
            self.save_metadata(metadata)
            logger.info(f"视频记录已添加: {filename} -> {original_name}")
            return True
        except Exception as e:
            logger.error(f"添加视频记录失败: {e}")
            return False
    
    def get_video_list(self) -> List[Dict]:
        """获取视频列表"""
        try:
            metadata = self.load_metadata()
            video_list = []
            
            for filename, info in metadata.items():
                file_path = self.upload_dir / filename
                if file_path.exists():
                    # 获取实际文件大小
                    actual_size = file_path.stat().st_size
                    video_info = {
                        "filename": filename,
                        "original_name": info.get("original_name", filename),
                        "file_size": actual_size,
                        "file_size_mb": round(actual_size / (1024 * 1024), 2),
                        "upload_time": info.get("upload_time", "未知"),
                        "video_url": info.get("video_url", f"{settings.VIDEO_BASE_URL}/videos/{filename}"),
                        "exists": True
                    }
                    video_list.append(video_info)
                else:
                    # 文件不存在，标记为已删除
                    video_info = {
                        "filename": filename,
                        "original_name": info.get("original_name", filename),
                        "file_size": info.get("file_size", 0),
                        "file_size_mb": round(info.get("file_size", 0) / (1024 * 1024), 2),
                        "upload_time": info.get("upload_time", "未知"),
                        "video_url": info.get("video_url", ""),
                        "exists": False
                    }
                    video_list.append(video_info)
            
            # 按上传时间倒序排列
            video_list.sort(key=lambda x: x["upload_time"], reverse=True)
            return video_list
            
        except Exception as e:
            logger.error(f"获取视频列表失败: {e}")
            return []
    
    def delete_video(self, filename: str) -> bool:
        """删除视频文件和记录"""
        try:
            # 删除物理文件
            file_path = self.upload_dir / filename
            if file_path.exists():
                file_path.unlink()
                logger.info(f"视频文件已删除: {file_path}")
            
            # 删除对应的视频分段
            # video_id是文件名去掉扩展名
            video_id = Path(filename).stem
            self._cleanup_video_segments(video_id)
            
            # 删除元数据记录
            metadata = self.load_metadata()
            if filename in metadata:
                del metadata[filename]
                self.save_metadata(metadata)
                logger.info(f"视频记录已删除: {filename}")
            
            return True
            
        except Exception as e:
            logger.error(f"删除视频失败: {e}")
            return False
    
    def _cleanup_video_segments(self, video_id: str) -> bool:
        """清理视频分段文件"""
        try:
            segments_dir = Path(settings.UPLOAD_DIR) / "segments" / video_id
            if segments_dir.exists():
                import shutil
                shutil.rmtree(segments_dir)
                logger.info(f"视频分段已删除: {video_id}")
                return True
            return False
        except Exception as e:
            logger.error(f"清理视频分段失败: {e}")
            return False
    
    def get_video_info(self, filename: str) -> Optional[Dict]:
        """获取单个视频信息"""
        try:
            metadata = self.load_metadata()
            if filename in metadata:
                info = metadata[filename]
                file_path = self.upload_dir / filename
                
                return {
                    "filename": filename,
                    "original_name": info.get("original_name", filename),
                    "file_size": info.get("file_size", 0),
                    "upload_time": info.get("upload_time", "未知"),
                    "video_url": info.get("video_url", f"{settings.VIDEO_BASE_URL}/videos/{filename}"),
                    "exists": file_path.exists()
                }
            return None
            
        except Exception as e:
            logger.error(f"获取视频信息失败: {e}")
            return None
    
    def cleanup_orphaned_records(self) -> int:
        """清理孤立的记录（文件已删除但记录仍存在）"""
        try:
            metadata = self.load_metadata()
            orphaned_count = 0
            
            for filename in list(metadata.keys()):
                file_path = self.upload_dir / filename
                if not file_path.exists():
                    del metadata[filename]
                    orphaned_count += 1
            
            if orphaned_count > 0:
                self.save_metadata(metadata)
                logger.info(f"清理了 {orphaned_count} 个孤立记录")
            
            return orphaned_count
            
        except Exception as e:
            logger.error(f"清理孤立记录失败: {e}")
            return 0